package com.future.common.plugins;

import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOServer;
import com.future.common.bean.Chat;
import com.future.common.global.PlatFormContext;
import com.future.common.listener.nettysocketio.ChatListener;
import com.future.common.listener.nettysocketio.ConnectedListener;
import com.future.common.listener.nettysocketio.DisconnectListener;
import com.jfinal.aop.Aop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.IPlugin;

import cn.hutool.core.util.NetUtil;

/**
 * netty SocketIo支持 启动socket服务端 主要用于消息推送服务
 * 参考
 * 	https://www.jb51.net/article/108633.htm
	https://blog.csdn.net/qing_gee/article/details/52525677
	https://www.cnblogs.com/always-online/p/4131635.html
 * @author Leon.Zhang
 *
 */
public class SocketIoPlugin implements IPlugin {
	private SocketIOServer server;
	@Override
	public boolean start() {
		boolean enableSocketio = PropKit.getBoolean("enableSocketio", false);
		if (enableSocketio) {
			Configuration config = new Configuration();
			config.setHostname(NetUtil.getLocalhostStr());
			config.setPort(PropKit.getInt("port", 9001));
			config.setContext("/communicate");
			//认证
			config.setAuthorizationListener(Aop.inject(new com.future.common.listener.nettysocketio.AuthorizationListener()));
			this.server = new SocketIOServer(config);
			//连接server
			server.addConnectListener(Aop.inject(new ConnectedListener()));
			//断开server
			server.addDisconnectListener(Aop.inject(new DisconnectListener()));
			server.addEventListener("chat", Chat.class, Aop.inject(new ChatListener()));
			PlatFormContext.setServer(this.server);
			this.server.start();
		}

		return true;
	}

	@Override
	public boolean stop() {
		if(this.server!=null){
			this.server.stop();
		}
		return true;
	}

}
